/*
 * Copyrignt (c) xuzeshui.com. All Rights Reserved.
 * Author: Zeshui Xu<i@xuzeshui.com>
 * Created Time: 2015-11-29 17:46:48
 * Last Modified: 2017-04-19 16:39:52
 * File Name: controllers/ip.go
 * Description:
 */

package controllers

import (
	"strings"

	"openapi/errorcode"
	"openapi/ip"
)

type IPController struct {
	BaseController
}

// 单个IP查询
// @router /location [get]
func (p *IPController) IPLocation() {
	defer p.Output("IPLocation")
	ipaddr := p.GetString("ip", "")
	clientIP := p.Ctx.Input.IP()
	if ipaddr == "" {
		ipaddr = clientIP
	}
	ipItem := ip.IPLocation(ipaddr)
	p.Resp["client_ip"] = clientIP
	p.Resp["ip"] = ipaddr
	if ipItem != nil {
		p.Resp["code"] = 0
		p.Resp["msg"] = "success"
		p.Resp["data"] = ipItem
	} else {
		p.Resp["code"] = errorcode.EC_IP_INVALID_IP
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_IP_INVALID_IP)
	}
}

//批量IP查询
// @router /location-batch [get]
func (p *IPController) IPLocationBatch() {
	defer p.Output("IPLocationBatch")
	ipaddrs := p.GetString("ips", "")
	p.Resp["client_ip"] = p.Ctx.Input.IP()
	addrs := strings.Split(ipaddrs, ",")
	if len(addrs) > 500 {
		p.Resp["code"] = errorcode.EC_IP_OVER_BATCH_QUERY_MAX_LENGTH
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_IP_OVER_BATCH_QUERY_MAX_LENGTH)
		return
	}
	ipdata := make(map[string]*ip.IPItem)
	for _, ipaddr := range addrs {
		if _, ok := ipdata[ipaddr]; ok {
			continue
		}
		if ipItem := ip.IPLocation(ipaddr); ipItem != nil {
			ipdata[ipaddr] = ipItem
		}
	}
	p.Resp["code"] = errorcode.EC_GL_SUCCESS
	p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_SUCCESS)
	p.Resp["ipdata"] = ipdata
}
